﻿$('#updateDay').click(submitTasks);

function submitTasks() {
    var taskModels = [];
    var dayToUpdate = $('#dayTableInfo').data('date');
    var updateUrl = $('#dayTableInfo').data('update-day-url');
    var notes = $('#Notes').val();

    $('#dayTable > tbody > tr').each(function () {
        var model = {
            Id: $(this).find('td.taskId').html(),
            Complete: $(this).find('td.taskIsComplete > input').is(':checked')
        };

        taskModels.push(model);
    });

    var jsonString = JSON.stringify({
        Date: dayToUpdate,
        Notes: notes,
        TasksToUpdate: taskModels
    });

    $.ajax({
        url: updateUrl,
        data: jsonString,
        contentType: 'application/json',
        type: 'POST',
    })
    .success(function (data) {
        if (data.Success) {
            writeSuccess(data.Message);
        } else {
            writeSuccess(data.Message);
        }
    })
    .fail(function () {
        writeError('Could not contact server to update tasks.')
    });
}

function writeSuccess(message) {
    $('#dayTableAlert').removeAttr('hidden').addClass('alert-success').html(message);
}

function writeError(message) {
    $('#dayTableAlert').removeAttr('hidden').addClass('alert-danger').html(message);
}